<?php
class Mysql
{
	var $conn;
	var $db_host;
	var $db_port;
	var $db_user;
	var $db_password;
	var $db_database;
	var $db_charset;
	var $p_connect;
	var $is_debug;
	function Mysql($db_host, $db_port = '3306', $db_user = 'root', $db_password = '', $db_database = '',$db_charset = 'latin1', $p_connect = 0, $debug = false)
	{
		$this->db_host=$db_host;
		$this->db_port=$db_port;
		$this->db_user=$db_user;
		$this->db_password=$db_password;
		$this->db_database=$db_database;
		$this->db_charset=$db_charset;
		$this->p_connect=$p_connect;
		$this->is_debug=$debug;
		$this->conn = $this->connect();
		$this->set_charset();
		$this->select_db();
	}
	function connect()
	{
		if(!$this->conn)
		{
			$conn = false;
			if($this->p_connect)
			{
				$conn = mysql_pconnect($this->db_host.':'.$this->db_port, $this->db_user, $this->db_password);
			}
			if(!$conn) 
			{
				$conn = mysql_connect($this->db_host.':'.$this->db_port, $this->db_user, $this->db_password,true);
			}
			if($conn)
			{
				unset($this->db_host);
				unset($this->db_password);
				unset($this->db_user);
				return $conn;
			}
			else 
			{
				$this->print_err(mysql_error());
			}
		}
		return $this->conn;
	}
	function select_db()
	{
		if(!$this->conn)
		{
			$this->connect();
		}
		if($this->conn)
		{
			return mysql_select_db($this->db_database,$this->conn);
		}
	}
	function set_charset()
	{
		if(!$this->conn)
		{
			$this->connect();
		}
		$version = mysql_get_server_info($this->conn);
        /* 如果mysql 版本是 4.1+ 以上，需要对字符集进行初始化 */
        if ($version > '4.1')
        {
            if ($this->db_charset != 'latin1')
            {
                mysql_query("SET character_set_connection='{$this->db_charset}', character_set_results='{$this->db_charset}', character_set_client=binary", $this->conn);
            }
            if ($version > '5.0.1')
            {
                mysql_query("SET sql_mode=''", $this->conn);
            }
        }
	}
	function query($sql)
	{
		if(!$this->conn)
		{
			$this->connect();
		}
		if($this->conn)
		{
			if($result = mysql_query($sql, $this->conn)) 
			{
				return $result;
			}
			else
			{
				$this->print_err(mysql_error());
			}
		}
	}
	function fetch_array($result,$result_type = MYSQL_BOTH)
	{
		return mysql_fetch_array($result,$result_type);
	}
	function close()
	{
		if($this->conn)
		{
			return mysql_close($this->conn);
		}
	}
	
	function __destruct()
	{
		if($this->conn)
		{
			$this->close();
		}
	}
	function print_err($err)
	{
		if($this->is_debug)
		{
			die($err);
		}
	}
	function insert_id()
	{
		return mysql_insert_id($this->conn);
	}
}	
?>